package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.dto.product.ProductContactAddDto;
import com.pactera.madp.cp.api.dto.product.ProductContactQueryDto;
import com.pactera.madp.cp.api.entity.product.ProdContactEntity;
import com.pactera.madp.cp.api.vo.product.ProductContactVO;
import com.pactera.madp.cp.api.vo.product.ProductLoveVO;
import com.pactera.madp.cp.common.constant.ProductConstant;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.ProdContactMapper;
import com.pactera.madp.cp.service.ProdContactService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (CpProdContact)表服务实现类
 *
 * @author yushen.qi
 * @since 2021-12-15 16:58:02
 */
@Slf4j
@Service("prodContactService")
@Transactional(rollbackFor = Exception.class)
public class ProdContactServiceImpl extends ServiceImpl<ProdContactMapper, ProdContactEntity> implements ProdContactService {

    /**
     * 事件类型，浏览
     */
    private static final String OPENING ="opening";
    /**
     * 事件类型，推荐
     */
    private static final String RECOMMEND ="recommend";

    @Resource
    private ProdContactMapper prodContactMapper;
    @Override
    public void countProd(ProductContactAddDto productContactAddDto, String url, String type, HttpServletResponse response) {
        ProdContactEntity prodContactEntity = new ProdContactEntity();
        BeanUtil.copyProperties(productContactAddDto,prodContactEntity);
        Integer corpId = productContactAddDto.getCorpId();
        prodContactEntity.setCorpId(corpId);
        prodContactEntity.setUpdateTime(LocalDateTime.now());
        log.info(StrUtil.format("》》》》》》》》》产品行为：{}",type));
                switch (type){
                    case   ProductConstant.OPENING:
                        getOpenCount(prodContactEntity,url,corpId,response);
                        break;
                    case   ProductConstant.RECOMMEND:
                        getRecommendCount(prodContactEntity);
                        break;
                    case   ProductConstant.PURCHASE:
                        getPurchaseCount(prodContactEntity,corpId);
                        break;
                    default:
                        throw new CheckedException("产品统计类型传输错误！");
                }
    }

    @Override
    public ProductLoveVO getProduct() {
        DateTime dateTime = new DateTime();
        String endTime = dateTime.toString();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String startTime = simpleDateFormat.format(dateTime);
        String opening = prodContactMapper.reqCount(OPENING);
        String openingToday = prodContactMapper.reqCountToday(OPENING,startTime,endTime);
        String recommend = prodContactMapper.reqCount(RECOMMEND);
        String recommendToday = prodContactMapper.reqCountToday(RECOMMEND,startTime,endTime);
        ProductLoveVO productLoveVO = new ProductLoveVO();
        productLoveVO.setProdLoveName(opening);
        productLoveVO.setProdRecommendName(recommend);
        productLoveVO.setTodayProdLoveName(openingToday);
        productLoveVO.setTodayProdRecommendName(recommendToday);
        return productLoveVO;
    }

    @Override
    public List<ProdContactEntity> getContactProd(String contactId) {
        Integer corpId = CorpContextHolder.getCorpId();
        List<ProdContactEntity> list = list(Wrappers.<ProdContactEntity>lambdaQuery().eq(ProdContactEntity::getContactId, contactId)
                .eq(ProdContactEntity::getCorpId, corpId)
                .orderByDesc(ProdContactEntity::getOpening).last("limit 3"));
        return list;
    }

    @Override
    public Page<ProductContactVO> getPage(Page page, ProductContactQueryDto req) {
        String sort=null;
         if(req.isOpening()){
             sort="opening";
         }else if (req.isRecommend()){
             sort="recommend";
         }else if (req.isPurchase()){
             sort="purchase";
         }else {
             sort="prod_id";
         }
         prodContactMapper.pageOne(page, req.getProductType(), sort)
                .getRecords().stream().peek(entity -> entity.setOuting(entity.getOpening() - entity.getPurchase()))
                .collect(Collectors.toList());
        return page;
    }


    /**
     * 统计客户浏览次数
     *
     * @param prodContactEntity 实体类
     * @param url 产品链接
     * @param response 响应对象
     */
    private void getOpenCount(ProdContactEntity prodContactEntity, String url,Integer corpId,HttpServletResponse response){
        try{
            int openTimes = Integer.parseInt(getObj(Wrappers.<ProdContactEntity>lambdaQuery().select(ProdContactEntity::getOpening)
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId()), Object::toString));
            prodContactEntity.setOpening(openTimes+1);
            boolean update = this.update(prodContactEntity, Wrappers.<ProdContactEntity>lambdaQuery()
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId())
                    .eq(ProdContactEntity::getCorpId,corpId));
            if(!update){
                log.error("统计次数失败:"+update);
                }
            log.error("重定向的链接："+url);
            response.sendRedirect(url);
        }catch (Exception e){
            log.error("统计次数失败:"+e.getMessage());
        }
    }
    /**
     * 统计产品推荐次数
     *
     * @param prodContactEntity 实体类
     */
    private void getRecommendCount(ProdContactEntity prodContactEntity){
        try{
            ProdContactEntity one = getOne(Wrappers.<ProdContactEntity>lambdaQuery()
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId()));
            if(one==null){
                prodContactEntity.setRecommend(1);
                prodContactEntity.setCreateTime(LocalDateTime.now());
                save(prodContactEntity);
            }else {
            int recommend = Integer.parseInt(getObj(Wrappers.<ProdContactEntity>lambdaQuery().select(ProdContactEntity::getRecommend)
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId()), Object::toString));
            prodContactEntity.setRecommend(recommend+1);
            boolean update = this.update(prodContactEntity, Wrappers.<ProdContactEntity>lambdaQuery()
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId())
                    .eq(ProdContactEntity::getCorpId,CorpContextHolder.getCorpId()));
            if(!update){
                log.error("统计次数失败:");
               }
            }
        }catch (Exception e){
            log.error("统计次数失败:"+e.getMessage());
        }
    }
    /**
     * 统计客户购买次数
     *
     * @param prodContactEntity 实体类
     */
    private void getPurchaseCount(ProdContactEntity prodContactEntity, Integer corpId){
        try{
            int purchase = Integer.parseInt(getObj(Wrappers.<ProdContactEntity>lambdaQuery().select(ProdContactEntity::getPurchase)
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId()).eq(ProdContactEntity::getContactId, prodContactEntity.getContactId()), Object::toString));
            prodContactEntity.setPurchase(purchase+1);
            boolean update = this.update(prodContactEntity, Wrappers.<ProdContactEntity>lambdaQuery()
                    .eq(ProdContactEntity::getProdId, prodContactEntity.getProdId())
                    .eq(ProdContactEntity::getContactId, prodContactEntity.getContactId())
                    .eq(ProdContactEntity::getCorpId,corpId));
            if(!update){
                log.error("统计次数失败:");
              }
        }catch (Exception e){
            log.error("统计次数失败:"+e.getMessage());
        }
    }

}
